

// 获取视频和 canvas 元素
const video = document.getElementById('camera');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 目标检测模型
let model;

// 加载 coco-ssd 模型
export async function loadModel() {
    try {
        model = await cocoSsd.load();
        console.log('coco-ssd model loaded');
        startDetection(); // 模型加载完成后开始目标检测
    } catch (error) {
        console.error('模型加载失败:', error);
    }
}

// 启动视频流并开始目标检测
export function startVideoStream() {
    navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
            video.srcObject = stream;
            video.play();
            video.onloadedmetadata = () => {
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                loadModel(); // 加载模型
            };
        })
        .catch(err => {
            console.error('无法访问摄像头:', err);
            alert('无法访问摄像头，请检查摄像头权限');
        });
}

// 目标检测函数
async function startDetection() {
    setInterval(async () => {
        // 将视频帧绘制到 canvas 上
        ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空 canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height); // 绘制视频帧

        // 使用 coco-ssd 模型进行检测
        const predictions = await model.detect(canvas);

        // 绘制检测到的框框
        predictions.forEach(prediction => {
            if (prediction.class === 'person') { // 只绘制人体目标框
                ctx.beginPath();
                ctx.rect(prediction.bbox[0], prediction.bbox[1], prediction.bbox[2], prediction.bbox[3]);
                ctx.lineWidth = 3;
                ctx.strokeStyle = 'red';
                ctx.fillStyle = 'red';
                ctx.stroke();
                ctx.fillText(prediction.class, prediction.bbox[0], prediction.bbox[1] > 10 ? prediction.bbox[1] - 5 : 10);
            }
        });

    }, 100); // 每100ms进行一次检测
}
